package net.caixiaomi.info.ui.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.Lottery.ui.LotteryOrderDetailActivity;
import net.caixiaomi.info.R;
import net.caixiaomi.info.adapter.OrderRecordAdapter;
import net.caixiaomi.info.base.BaseFragment;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.base.quickadapter.BaseQuickAdapter;
import net.caixiaomi.info.interfaces.ComonFragmentImpl;
import net.caixiaomi.info.logger.Timber;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.OrderRecordItem;
import net.caixiaomi.info.model.OrderRecordModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.smartrefresh.layout.SmartRefreshLayout;
import net.caixiaomi.smartrefresh.layout.api.RefreshLayout;
import net.caixiaomi.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import butterknife.BindView;
import icepick.State;
import retrofit2.Call;

import static android.R.id.list;

/**
 * 订单列表
 * <p>
 * public static final Integer ORDER_STATUS_NOT_PAY = 0;         //待付款
 * public static final Integer ORDER_STATUS_PAY_FAIL_LOTTERY = 1;//待出票
 * public static final Integer ORDER_STATUS_FAIL_LOTTERY = 2;    //出票失败
 * public static final Integer ORDER_STATUS_STAY = 3;            //待开奖
 * public static final Integer ORDER_STATUS_NOT = 4;             //未中奖
 * public static final Integer ORDER_STATUS_ALREADY = 5;         //已中奖
 */

public class OrderRecordFragment extends BaseFragment implements ComonFragmentImpl, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemClickListener, OnRefreshListener {

    @BindView(R.id.refresh)
    SmartRefreshLayout mRefresh;
    @BindView(list)
    RecyclerView mListView;
    @BindView(R.id.progress)
    CircularProgressBar mProgress;
    @State
    int mType;
    private int mPageNum = 1;
    private OrderRecordAdapter mAdapter;

    @Override
    protected int fragmentLayout() {
        return R.layout.frag_common_list;
    }

    @Override
    protected void onFragmentCreated(View view, @Nullable Bundle savedInstanceState) {
        mRefresh.setOnRefreshListener(this);
        mListView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mAdapter = new OrderRecordAdapter(R.layout.item_order_record);
        mAdapter.setOnLoadMoreListener(this, mListView);
        mAdapter.setOnItemClickListener(this);
        TextView textView = (TextView) LayoutInflater.from(getActivity()).inflate(R.layout.empty, null);
        textView.setText(R.string.C_NO_PURCHASE_RECORDER_DATA);
        mAdapter.setEmptyView(textView);
        mListView.setAdapter(mAdapter);
        mAdapter.setEnableLoadMore(true);
        loadData();
    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("pageNum", mPageNum);
        params.put("pageSize", Constants.PAGE_SIZE);
        params.put("lotteryClassifyId", "1");
        params.put("orderStatus", mType);
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<OrderRecordModel>> getOrderInfoList = requestService.getOrderInfoList(params);
        getOrderInfoList.enqueue(new ResponseCallback<BaseCallModel<OrderRecordModel>>(getActivity()) {
            @Override
            public void onSuccess(BaseCallModel<OrderRecordModel> data) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                OrderRecordModel model = data.data;
                if (model != null) {
                    List<OrderRecordItem> list = model.getList();
                    if (mPageNum == 1) {
                        mAdapter.setNewData(list);
                    } else {
                        mAdapter.addData(list);
                        mAdapter.loadMoreComplete();
                    }
                    mAdapter.notifyDataSetChanged();
                    boolean hasNextPage = Boolean.valueOf(model.getHasNextPage());
                    mAdapter.setEnableLoadMore(hasNextPage);
                }
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                if (mPageNum != 1) {
                    mAdapter.loadMoreComplete();
                }
                mPageNum = mAdapter.getData().size() % Integer.valueOf(Constants.PAGE_SIZE) == 0 ? mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) : mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) + 1;
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }
            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
                mRefresh.finishRefresh();
                if (mPageNum != 1) {
                    mAdapter.loadMoreComplete();
                }
                mPageNum = mAdapter.getData().size() % Integer.valueOf(Constants.PAGE_SIZE) == 0 ? mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) : mAdapter.getData().size() / Integer.valueOf(Constants.PAGE_SIZE) + 1;
            }
        });
    }

    @Override
    public void setType(int type) {
        mType = type;
    }

    @Override
    public void setFilter(String filter) {

    }

    @Override
    public void onLoadMoreRequested() {
        mPageNum++;
        Timber.d("onLoadMoreRequested " + mPageNum);
        loadData();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        try {
            OrderRecordItem orderRecordItem = mAdapter.getData().get(position);
            if(TextUtils.equals(orderRecordItem.getLotteryName(),"大乐透")){
                Intent intent = new Intent(getActivity(), LotteryOrderDetailActivity.class);
                intent.putExtra("id", orderRecordItem.getOrderId());
                startActivity(intent);
            }else{
                Intent intent = new Intent(getActivity(), OrderInfoActivity.class);
                intent.putExtra("id", orderRecordItem.getOrderId());
                startActivity(intent);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        mPageNum = 1;
        loadData();
    }
}
